/*******************************************************************************
 * Copyright (c) 2011 Grupo de Sistemas Inteligentes (GSI) - DIT UPM
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package es.upm.dit.gsi.eclipse.jadex.adfmanager.actions;

import java.io.File;
import java.lang.reflect.InvocationTargetException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.IActionDelegate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import es.upm.dit.gsi.eclipse.jadex.navigator.SubChild;

public class DeleteSubChild implements IActionDelegate {
	ISelection _selection;
	
	public DeleteSubChild () {
		super();
	}


	@Override
	public void run(IAction action) {
		final SubChild selSubChild = getSelectedSubChild();
		final IFile agentFile = getSelectedSubChildAgentFile();
		final String parentNodeName = getSelectedSubChild().getContainer().getName();
		
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					deleteNode(agentFile, selSubChild, parentNodeName);
				} catch (Exception e) {
					e.printStackTrace();
					throw new InvocationTargetException(e);
				} finally {
				}
			}
		};
		
		try {
			op.run(null);
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		_selection = selection;
	}
	
	
	private SubChild getSelectedSubChild(){
		if(_selection instanceof TreeSelection){		
			SubChild selectedSubChild = (SubChild)((TreeSelection)_selection).getFirstElement();
			return  selectedSubChild;
		}
		return null;
	}
	
	private IFile getSelectedSubChildAgentFile(){
		SubChild s = getSelectedSubChild();
		if(s != null){
			return s.getContainer().getContainer();
		}
		return null;
	}
	
	/*
	 * PRIVATE METHOD IN ORDER TO MODIFY A XML FILE
	 */
	private void deleteNode(IFile agentFile, SubChild selSubChild, String parentNode) 
		throws Exception{
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(agentFile.getRawLocation().toOSString());
		
		
	 
		//Get the events element 
		Node category = doc.getElementsByTagName(parentNode).item(0);
		NodeList nodeList =  category.getChildNodes();
		for(int i = 0; i < nodeList.getLength() ; i++){
			Node node = nodeList.item(i);
			if(!node.getNodeName().equals("#comment") && !node.getNodeName().equals("#text")){
				Element e = (Element)node;
					if(e.getAttribute("name").equals(selSubChild.getDescription())){
						category.removeChild(nodeList.item(i));
					}
			}
		}
		
		
		//write the content into xml file
	    
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
	    transformerFactory.setAttribute("indent-number", new Integer(4));
	    Transformer transformer;
		transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	    DOMSource source = new DOMSource(doc);
	    StreamResult result =  new StreamResult(new File(agentFile.getRawLocation().toOSString()));
	    transformer.transform(source, result);
	    agentFile.refreshLocal(IFile.DEPTH_INFINITE, null);
		}
}	
